//
//  FoundServiceViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/9/3.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "FoundServiceViewController.h"

#import "MeatShopListViewController.h"
#import "MeaetCityFriendHeader.h"
#import "FoundServiceCell.h"

#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

#import "MeatMarketApi.h"
#import "MKMapView+ZoomLevel.h"
#import "MyAnnotation.h"
#import "CustomPinAnnotationView.h"

#define kHeaderHeight 400
#define ZOOM_LEVEL 17
#define shopCellHeight 54.0


@interface FoundServiceViewController ()<CLLocationManagerDelegate, MKMapViewDelegate>

@property (strong, nonatomic) UIButton *leftNavBtn;

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, strong) CLLocation *useLocation; //当前地址
@property (nonatomic, strong) UIImageView *bigPin; //大头针

@property (nonatomic, strong) MeatMarketApi *meatApi;
@property (nonatomic, strong) MeatShopNearByPage *model;

@property (nonatomic, strong) NSMutableArray *datas;
@property (nonatomic, assign) BOOL isUpdateLocation; //是否更新位置
@property (nonatomic, assign) BOOL isFristPositioning; //是否是第一次定位
@property (nonatomic, assign) BOOL isChooseUpdateLocation; //是否选择更新位置
@property (nonatomic, strong) AMapPOI *fristMapPOI; //定位地址数据

@property (nonatomic, strong) UIView *greenCircle;

@property (nonatomic, strong) UIImageView *shopMenu;



@end

@implementation FoundServiceViewController

#pragma mark - lifecycle methods

- (void)setupUI{
    
    self.baseNavView.hidden  = YES;
    [self.view addSubview:self.mapView];
    [self.view addSubview:self.leftNavBtn];
    
    [self requestMapData];
}

- (void)setupLayout{
    
    {
        self.reloadBtn.mj_y -= 100;
        self.reloadLab.mj_y -= 100;
    }
    
    {
        _leftNavBtn.frame = CGRectMake(15, TJ_StatusBarHeight_Define, 44,  44);
    }

    {
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.right.left.bottom.mas_equalTo(0);
            make.top.mas_equalTo(self.mapView.bottom);
        }];
    }
}

#pragma mark - networking methods

- (void)initData{
    
    NSNumber *page = [NSNumber numberWithInteger:self.page];
    FoundMapNearByParam *parma= [[FoundMapNearByParam alloc] init];
    parma.memberId = kMemberId;
    parma.page = page;
    parma.limit = @10;
    parma.latitude = @"39.421598";
    parma.longitude = @"117.054445";
    [self requsetNearbyServiceByParam:parma];
}

//- (void)requestNearByListByParam:(MeatShopNearByParam *)param{
//
//    @weakify(self);
//    [[self.meatApi getMeatShopNearByListByParam:param] subscribeNext:^(MeatShopNearByModel * _Nullable model) {
//        @strongify(self)
//
//        if (self.isRefresh) {
//
//            [self endRefresh];
//            if (self.datas.count >0) {
//                [self.datas removeAllObjects];
//            }
//        }
//
//        self.model = model.page;
//        [self.model.list enumerateObjectsUsingBlock:^(MeatShopNearByItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//
//            MyAnnotation *myPinModel = [[MyAnnotation alloc] init];
//            CLLocationCoordinate2D coor ;
//            coor.latitude = [obj.nowLatitude doubleValue];
//            coor.longitude = [obj.nowLongitude doubleValue];
//            myPinModel.coordinate = coor;
//            myPinModel.type = obj.sex;
//            myPinModel.imageUrl = obj.headImg;
//            [self.mapView addAnnotation:myPinModel];
//            [self.datas addObject:obj];
//        }];
//
//
//        if ([self.model.currPage intValue] >= [self.model.totalPage intValue]) {
//            [self endLoadMoreMoData];
//        }else{
//            [self endLoadMore];
//        }
//
//        if (self.datas.count >0) {
//            self.tableView.hidden = NO;
//            [self.tableView reloadData];
//        }else{
//            [self loadNoData];
//        }
//
//    }error:^(NSError * _Nullable error) {
//        @strongify(self);
//        [self loadErrorData];
//    }];
//}

- (void)requestMapData{
    
    [[[MeatFoundApi sharedInstance] getMapShowByLat:@"39.421598" lon:@"117.054445"] subscribeNext:^(FoundMapShowModel * _Nullable x) {
        
    } error:^(NSError * _Nullable error) {
        
    }];
}

- (void)addOrExitSerView{
    
    FoundServiceExitParam *param = [[FoundServiceExitParam alloc] init];
    param.memberId = kMemberId;
    param.type = @1;
    param.myMemberId = @1;
    
    [[[MeatFoundApi sharedInstance] getMapExitServiceByParams:param] subscribeNext:^(NSNull * _Nullable x) {
        
    } error:^(NSError * _Nullable error) {
        
    }];
}


- (void)requsetNearbyServiceByParam:(FoundMapNearByParam *)param{
    
    @weakify(self);
    [[[MeatFoundApi sharedInstance] getMapNearByByParams:param] subscribeNext:^(FoundMapNearByModel * _Nullable model) {
        @strongify(self)
        
        if (self.isRefresh) {
            
            [self endRefresh];
            if (self.datas.count >0) {
                [self.datas removeAllObjects];
            }
        }
        
        [model.list enumerateObjectsUsingBlock:^(FoundMapNearByItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.datas addObject:obj];
        }];
        
        if ([model.currPage intValue] >= [model.totalPage intValue]) {
            [self endLoadMoreMoData];
        }else{
            [self endLoadMore];
        }
        
        if (self.datas.count >0) {
            self.tableView.hidden = NO;
            [self.tableView reloadData];
        }else{
            [self loadNoData];
        }
        
    }error:^(NSError * _Nullable error) {
        @strongify(self);
        [self loadErrorData];
    }];
}

//下拉刷新
- (void)refresh
{
    [super refresh];
    [self resetData];
    [self initData];
}

//上拉加载更多
- (void)loadMore
{
    [super loadMore];
    
    NSNumber *page = [NSNumber numberWithInteger:self.page];
    FoundMapNearByParam *parma= [[FoundMapNearByParam alloc] init];
    parma.memberId = kMemberId;
    parma.page = page;
    parma.limit = @10;
    parma.latitude = @"39.421598";
    parma.longitude = @"117.054445";
    [self requsetNearbyServiceByParam:parma];
}


#pragma mark -

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
    
    if (!animated && !_isFristPositioning ) {
        self.isFristPositioning = YES;
    }
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    [self.locationManager stopUpdatingLocation];
    
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = userLocation.location.coordinate.latitude;
    coordinate.longitude = userLocation.location.coordinate.longitude;
    [_mapView setCenterCoordinate:coordinate zoomLevel:ZOOM_LEVEL animated:NO];
    
    if (_isUpdateLocation) {
        _isUpdateLocation = NO;
        [self hideProgressView];
        [self setMapRegionWithCoordinate:coordinate];
    }
}


- (void)setMapRegionWithCoordinate:(CLLocationCoordinate2D)coordinate{
    
    MKCoordinateRegion region;
    region = MKCoordinateRegionMake(coordinate, MKCoordinateSpanMake(.01, .01));
    MKCoordinateRegion adjustedRegion = [_mapView regionThatFits:region];
    _isFristPositioning = YES;
    [_mapView setRegion:adjustedRegion animated:YES];
}


//更新用户位置，只要用户改变则调用此方法（包括第一次定位到用户位置）
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated { // 调用获取中心点坐标代理方法
    
    [self.locationManager stopUpdatingLocation];
    
    MKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate2D = mapView.region.center;
    region.center = centerCoordinate2D;
    
    if (self.isFristPositioning && _isChooseUpdateLocation) {
        
        self.isFristPositioning = NO;
        CLLocation *location = [[CLLocation alloc] initWithLatitude:centerCoordinate2D.latitude longitude:centerCoordinate2D.longitude];
        self.useLocation = location;
        
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        
        @weakify(self);
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            @strongify(self);
            CLPlacemark *place = [placemarks firstObject];
            self.fristMapPOI = [[AMapPOI alloc] init];
            NSString *address = [NSString stringWithFormat:@"%@%@%@", place.locality, place.subLocality, place.name];
            self.fristMapPOI.address = address;
            self.fristMapPOI.location.latitude = place.location.coordinate.latitude;
            self.fristMapPOI.location.longitude = place.location.coordinate.longitude;
            NSLog(@"%@", self.fristMapPOI.address);
        }];
        
    }else{
        _isChooseUpdateLocation = YES;
    }
    
    [self bigPinAnimation];
}


//大头针跳动的动画
- (void)bigPinAnimation{
    
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        
        CGPoint center = self.bigPin.center;
        center.y -= 20;
        [self.bigPin setCenter:center];
        
    } completion:nil];
    
    [UIView animateWithDuration:0.45 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        
        CGPoint center = self.bigPin.center;
        center.y += 20;
        [self.bigPin setCenter:center];
        
    } completion:nil];
}


- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        MKAnnotationView *annotationView = [[MKAnnotationView alloc]init];
        annotationView.image = [UIImage imageNamed:@"address_map_circle"];
        annotationView.canShowCallout = YES;
        return annotationView;
    }
    
    
    CustomPinAnnotationView *annotationView = (CustomPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"otherAnnotationView"];
    if (annotationView == nil) {
        annotationView = [[CustomPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"otherAnnotationView"];
    }
    
    MyAnnotation *myAnnotation = annotation;
    annotationView.imageUrl = myAnnotation.imageUrl;
    
    switch ([myAnnotation.type intValue]) {
        case PinType_Man:
            annotationView.image = [UIImage imageNamed:@"address_map_mark_man"];
            break;
        case PinType_Wonman:
            annotationView.image = [UIImage imageNamed:@"address_map_mark_woman"];
            break;
        default:
            break;
    }
    
    return annotationView;
}

//大头针显示在视图上时调用，在这里给大头针设置显示动画
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray<MKAnnotationView *> *)views{
    
    
    //    获得mapView的Frame
    CGRect visibleRect = [mapView annotationVisibleRect];
    
    for (MKAnnotationView *view in views) {
        
        CGRect endFrame = view.frame;
        CGRect startFrame = endFrame;
        startFrame.origin.y = visibleRect.origin.y - startFrame.size.height;
        view.frame = startFrame;
        [UIView beginAnimations:@"drop" context:NULL];
        [UIView setAnimationDuration:1];
        view.frame = endFrame;
        [UIView commitAnimations];
        
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (self.shopMenu.alpha == 1) {
        [self hideShopMenu];
    }
}

#pragma mark - tableview.datasource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.datas.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 55;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    MeaetCityFriendHeader *sectionView = [[MeaetCityFriendHeader alloc] init];
    sectionView.titleLab.text = @"附近的服务商";
    return sectionView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FoundServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FoundServiceCell"];
    
    if (indexPath.row < self.datas.count) {
        FoundMapNearByItem *item = self.datas[indexPath.row];
        cell.item  = item;
        
        @weakify(self);
        cell.dealServiceBlock = ^{
            @strongify(self);
            
            [self showMyAlertWithTitle:@"附近服务商" message:@"您确定要选ta作为您的服务商并加为好友吗？" confirmBtnTitle:@"确定" callBack:^{
            }];
        };
    }
    return cell;
}


- (void)showShopMenu{
    
    @weakify(self);
    [UIView animateWithDuration:0.5 animations:^{
        @strongify(self);
        self.shopMenu.alpha = 1;
    }];
}

- (void)hideShopMenu{
    
    @weakify(self);
    [UIView animateWithDuration:0.5 animations:^{
        @strongify(self);
        self.shopMenu.alpha = 0;
    }];
}



#pragma mark - getter methods

- (void)registerTableViewCell{
    
    CGFloat kTableViewHeight = KScreenHeight - 192 - TJ_TabBarHeight;
    self.tableView.height = kTableViewHeight;
    self.tableView.separatorColor = mIconLineColor;
    self.tableView.rowHeight = 70;
    
    [self.tableView registerClass:[FoundServiceCell class] forCellReuseIdentifier:@"FoundServiceCell"];
}

- (UIButton *)leftNavBtn{
    
    if (!_leftNavBtn) {
        _leftNavBtn = [UIButton makeButtonWithImageName:@"nav_back"];
        _leftNavBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        
        kWeakSelf(self);
        _leftNavBtn.tapBlock = ^{
            [weakself.navigationController popViewControllerAnimated:YES];
        };
    }
    
    return _leftNavBtn;
}



//添加地图控件
- (MKMapView *)mapView{
    
    if (!_mapView) {
        
        _mapView = [[MKMapView alloc]initWithFrame:CGRectZero];
        _mapView.frame = CGRectMake(0, 0, KScreenWidth, kHeaderHeight);
        _mapView.delegate = self;
        
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        
        if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse){
            [_locationManager requestWhenInUseAuthorization];
        }else{
            [self showHudWithMsg:@"请开启定位功能"];
        }
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        
        //大头针
        [_mapView addSubview:self.bigPin];
        [_mapView addSubview:self.greenCircle];
    }
    return _mapView;
}


//大头针
- (UIImageView *)bigPin
{
    if (!_bigPin) {
        
        _bigPin = [[UIImageView alloc] init];
        _bigPin.image = [UIImage imageNamed:@"address_bigpin"];
        _bigPin.size = CGSizeMake(20, 40);
        _bigPin.mj_x = KScreenWidth/2.0 - 10;
        _bigPin.mj_y = kHeaderHeight/2.0 - 40;
    }
    return _bigPin;
}

- (UIView *)greenCircle{
    
    if (!_greenCircle) {
        _greenCircle = [UIView makeViewBgColor:UIColorFromRGB(0x52C102) cornerRadius:150];
        _greenCircle.alpha = 0.08;
        _greenCircle.size = CGSizeMake(300, 300);
        _greenCircle.mj_x = KScreenWidth/2.0 - 150;
        _greenCircle.mj_y = kHeaderHeight/2.0 - 150;
        _greenCircle.userInteractionEnabled = NO;
    }
    return _greenCircle;
}


- (UIImageView *)shopMenu{
    
    if (!_shopMenu) {
        _shopMenu = [UIImageView new];
        _shopMenu.image = [UIImage imageNamed:@"meat_city_bg"];
        _shopMenu.width = 144;
        _shopMenu.mj_x = KScreenWidth - _shopMenu.width - 50;
        _shopMenu.userInteractionEnabled = YES;
    }
    return _shopMenu;
}


- (MeatMarketApi *)meatApi{
    
    if(!_meatApi){
        _meatApi = [[MeatMarketApi alloc]init];
    }
    return _meatApi;
}


- (MeatShopNearByPage *)model{
    
    if (!_model) {
        _model = [[MeatShopNearByPage alloc] init];
    }
    return _model;
}

- (NSMutableArray *)datas{
    
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

@end
